package com.zmn.oms.api.controller.complaint;

import com.zmn.base.common.data.dubbo.interfaces.mobilecity.MobilecityListRemoteService;
import com.zmn.biz.complain.common.constant.DubboConsts;
import com.zmn.biz.complain.common.dio.complain.Chs58ComplainDIO;
import com.zmn.biz.complain.common.dio.complain.SimpleComplainCategoryDIO;
import com.zmn.biz.complain.common.dio.complain.outer.ChsComplainOuterDIO;
import com.zmn.biz.complain.common.dro.complain.Chs58ComplainDRO;
import com.zmn.biz.complain.common.dro.complain.outer.ChsComplainOuterDRO;
import com.zmn.biz.complain.dubbo.interfaces.complain.ChsComplain58ListRemoteService;
import com.zmn.biz.complain.dubbo.interfaces.complain.ChsComplain58ModifyRemoteService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.model.dto.order.proxy.ComplaintCategoryDTO;
import com.zmn.oms.model.dto.order.proxy.ComplaintDTO;
import com.zmn.oms.model.entity.comment.OrderComment;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.oms.model.vo.order.proxy.ComplaintOrderVO;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：旧平台投诉接口代理
 *
 * @author heciqi
 * @date 2019/03/02 17:35
 */
@RestController
@RequestMapping("/proxy/complaint")
@Slf4j
public class ProxyComplaintController {
	private Logger logger = LoggerFactory.getLogger(ProxyComplaintController.class);

	@Reference(version = DubboConsts.INTERFACE_VERSION,check = false)
	private ChsComplain58ListRemoteService chsComplain58ListRemoteService;
	@Reference(version = DubboConsts.INTERFACE_VERSION,check = false)
	private ChsComplain58ModifyRemoteService chsComplain58ModifyRemoteService;

	@Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION ,check = false)
	private MobilecityListRemoteService mobilecityListRemoteService;

	@Autowired
	private OrderWorkListBService orderWorkListBService;

	@Autowired
	private OrderWorkService orderWorkService;

	@Autowired
	private OrderDetailService orderDetailService;
	@Autowired
	private OrderCommentService orderCommentService;

	/**
	 * 根据outerId查询工单
	 *
	 * @return
	 */
	@RequestMapping("/orderwork/outerid/{outerId}")
	public ResultDTO findOrderWorkByOuterId(@PathVariable("outerId") String outerId) {
		if (StringUtils.isBlank(outerId)) {
			logger.error("outerId为空");
			return ResultDTO.fail("outerId为空");
		}

		OrderWorkQuery query = new OrderWorkQuery();
		query.setOuterId(outerId);
		query.setIncludes(Arrays.asList("orderId", "companyId", "companyName", "channelId", "channelName",
				"cityId", "cityName", "naturalCityId", "countyId", "countyName"));
		List<EsOrderWork> esOrderWorks = orderWorkListBService.listPageOrderWorkByQuery(query);
		if (CollectionUtils.isEmpty(esOrderWorks)) {
			return ResultDTO.fail("未找到outerId对应的工单数据");
		}


		ComplaintOrderVO complaintOrderVO = BeanMapper.map(esOrderWorks.get(0), ComplaintOrderVO.class);
		return ResultDTO.success(complaintOrderVO);
	}

	/**
	 * 根据outerId查询投诉
	 * @param outerId
	 * @return
	 */
	@RequestMapping("/outerid/{outerId}")
	public ResultDTO findComplaintByOuterId(@PathVariable("outerId") String outerId) {
		if (StringUtils.isBlank(outerId)) {
			logger.error("outerId为空");
			return ResultDTO.fail("outerId为空");
		}

		ResponseDTO<ChsComplainOuterDRO> chsComplainOuterDRO = chsComplain58ListRemoteService.getChsComplainOuterByThirdId(outerId);
		if (chsComplainOuterDRO.isSuccess() && chsComplainOuterDRO.getData() != null) {
			ChsComplainOuterDRO data = chsComplainOuterDRO.getData();
			ComplaintDTO complaintDTO = new ComplaintDTO();
			complaintDTO.setComplainId(data.getOuterId());
			complaintDTO.setThirdId(data.getThirdId());
			complaintDTO.setThirdData(data.getThirdData());
			return ResultDTO.success(complaintDTO);
		} else {
			logger.error("outerId:{}无数据", outerId);
			return ResultDTO.fail("outerId无数据");
		}
	}

	/**
	 * 根据投诉id查询投诉
	 *
	 * @return
	 */
	@RequestMapping("/id/{complaintId}")
	public ResultDTO findComplaintById(@PathVariable("complaintId") Integer complaintId) {
		// 投诉id获取数据
		ResponseDTO<ChsComplainOuterDRO> chsComplainOuterDRO = chsComplain58ListRemoteService.getChsComplainOuterByOuterId(complaintId);

		// 投诉第三方数据赋值
		ComplaintDTO complaintDTO = new ComplaintDTO();
		if (chsComplainOuterDRO.isSuccess() && chsComplainOuterDRO.getData() != null) {
			ChsComplainOuterDRO outerDRO = chsComplainOuterDRO.getData();
			complaintDTO.setComplainId(outerDRO.getOuterId());
			complaintDTO.setThirdId(outerDRO.getThirdId());
			complaintDTO.setThirdData(outerDRO.getThirdData());
		}


		ResponseDTO<Chs58ComplainDRO> chsComplainDROResp = chsComplain58ListRemoteService.getChsComplainByComplainId(complaintId);
		Chs58ComplainDRO chsComplainDRO = chsComplainDROResp.getData();
		if (!chsComplainDROResp.isSuccess() || chsComplainDRO == null) {
			return ResultDTO.fail(complaintId + "无投诉数据");
		}

		Long orderId = chsComplainDRO.getOrderId();
		Long workId = chsComplainDRO.getOrderId();// 投诉的订单id和工单id一致

		complaintDTO.setComplainId(chsComplainDRO.getComplainId());
		complaintDTO.setOrderId(orderId);
		complaintDTO.setStatus(chsComplainDRO.getStatus());
		complaintDTO.setResultStatus(chsComplainDRO.getResultStatus());
		complaintDTO.setLevel(chsComplainDRO.getLevel());
		complaintDTO.setSourceId(chsComplainDRO.getSourceId());
		complaintDTO.setCompanyId(chsComplainDRO.getCompanyId());
		complaintDTO.setRemark(chsComplainDRO.getResultStatusName());
		complaintDTO.setCreateTime(chsComplainDRO.getCreateTime());
		complaintDTO.setUpdateTime(chsComplainDRO.getUpdateTime());
		complaintDTO.setTel1(chsComplainDRO.getPhone());
		complaintDTO.setCityId(chsComplainDRO.getCityId());
		complaintDTO.setCountyId(chsComplainDRO.getCountryId());
		List<ComplaintCategoryDTO> categoryList = BeanMapper.mapList(chsComplainDRO.getComplainCategoryList(), ComplaintCategoryDTO.class);
		complaintDTO.setCategoryList(categoryList);

		// 补充投诉中的工单信息
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
		complaintDTO.setOrderOuterId(orderWork.getOuterId());
		complaintDTO.setOrderCityId(orderWork.getNaturalCityId());// 工单自然城市id
		complaintDTO.setOrderCityName(orderDetail.getNaturalCityName());// 工单自然城市名称
		com.zmn.common.dto2.ResponseDTO<String> responseDTO = mobilecityListRemoteService.getTelCodeByCityId(orderWork.getNaturalCityId()); // 电话区号
		complaintDTO.setOrderCityZone(responseDTO.getData());
		return ResultDTO.success(complaintDTO);
	}

	/**
	 * 创建投诉
	 *
	 * @param complaintDTO 投诉信息
	 * @return
	 */
	@PostMapping("/add")
	@ResponseBody
	public ResultDTO addComplaint(@Valid @RequestBody ComplaintDTO complaintDTO) {
		try {
			// 1，添加投诉
			Chs58ComplainDIO chs58ComplainDIO = BeanMapper.map(complaintDTO, Chs58ComplainDIO.class);
			chs58ComplainDIO.setOperator("系统");
			chs58ComplainDIO.setOperatorId(1); // 指定1，为接口创建
			List<SimpleComplainCategoryDIO> categoryList = BeanMapper.mapList(complaintDTO.getCategoryList(), SimpleComplainCategoryDIO.class);
			chs58ComplainDIO.setCategoryList(categoryList);// 投诉分分类
			// 渠道评分获取投诉等级
			if (complaintDTO.getOrderId() != null) {
				OrderComment comment = orderCommentService.findCommentByKey(complaintDTO.getOrderId());
				if (Objects.nonNull(comment) && Objects.equals(comment.getType(), OrderConsts.COMMENT_TYPE_THIRD)) {
					chs58ComplainDIO.setLevel(OrderConsts.getComplaintLevelByScore(comment.getScore()));
					logger.info("[{}]设置投诉等级为[{}]",complaintDTO.getOrderId(),chs58ComplainDIO.getLevel());
				}
			}
			ResponseDTO<Integer> addChsComplainResp = chsComplain58ModifyRemoteService.addChsComplain(chs58ComplainDIO);
			if (!addChsComplainResp.isSuccess() || addChsComplainResp.getData() == null) {
				logger.error("Remote添加投诉失败{}", addChsComplainResp.getMessage());
				return ResultDTO.fail(addChsComplainResp.getMessage());
			}
			Integer complaintId = addChsComplainResp.getData();

			// 2，添加投诉原始数据
			ChsComplainOuterDIO complainOuterDIO = new ChsComplainOuterDIO();
			complainOuterDIO.setOuterId(complaintId);
			complainOuterDIO.setThirdId(complaintDTO.getThirdId());
			complainOuterDIO.setThirdData(complaintDTO.getThirdData());
			complainOuterDIO.setCreater("sys");
			complainOuterDIO.setCreateTime(DateUtil.getNow());
			ResponseDTO<Boolean> addComplainOuterResp = chsComplain58ModifyRemoteService.addChsComplainOuter(complainOuterDIO);
			if (!addComplainOuterResp.isSuccess()) {
				logger.error("Remote添加投诉原始数据失败{}",addComplainOuterResp.getMessage());
				return ResultDTO.fail(addComplainOuterResp.getMessage());
			}

			return new ResultDTO(addComplainOuterResp.isSuccess());
		} catch (Exception e) {
			logger.error("添加投诉异常",e);
			return ResultDTO.fail("添加投诉异常：" + e.getMessage());
		}
	}

	/**
	 * 修改投诉
	 *
	 * @param complaintDTO 投诉信息
	 * @return
	 */
	@PostMapping("/update")
	@ResponseBody
	public ResultDTO updateComplaint(@Valid @RequestBody ComplaintDTO complaintDTO) {
		try {
			// 1，修改投诉原始数据
			ChsComplainOuterDIO outerDIO = new ChsComplainOuterDIO();
			outerDIO.setOuterId(complaintDTO.getComplainId());
			outerDIO.setThirdData(complaintDTO.getThirdData());
			ResponseDTO<Boolean> chsComplainOuterResp = chsComplain58ModifyRemoteService.modifyChsComplainOuter(outerDIO);
			if (!chsComplainOuterResp.isSuccess()) {
				logger.error("Remote修改投诉原始数据失败{}", chsComplainOuterResp.getMessage());
				return ResultDTO.fail(chsComplainOuterResp.getMessage());
			}

			// 2，修改投诉
			Chs58ComplainDIO chs58ComplainDIO = new Chs58ComplainDIO();
			chs58ComplainDIO.setComplainId(complaintDTO.getComplainId());
			chs58ComplainDIO.setContent(complaintDTO.getContent());
			chs58ComplainDIO.setStatus(complaintDTO.getStatus());
			chs58ComplainDIO.setRemark(complaintDTO.getRemark());
			chs58ComplainDIO.setOperator("系统");
			chs58ComplainDIO.setOperatorId(1);
			ResponseDTO<Boolean> chsComplainResp = chsComplain58ModifyRemoteService.setChsComplain(chs58ComplainDIO);
			if (!chsComplainResp.isSuccess()) {
				logger.error("Remote修改投诉失败{}", chsComplainResp.getMessage());
			}

			return new ResultDTO(chsComplainResp.isSuccess());
		} catch (Exception e) {
			logger.error("修改投诉异常",e);
			return ResultDTO.fail("修改投诉异常：" + e.getMessage());
		}
	}
}
